<template>
  <!-- 主聊天容器 -->
  <div class="chat-container">
  <!-- 左侧联系人列表 -->
    <div class="contact-sidebar" v-if="[1,2,3].includes(userRole)">
      <div class="sidebar-header">
        <h4>最近联系人</h4>
      </div>
      <div class="contact-list">
        <!-- 联系人项 -->
        <div class="contact-item" v-for="(contact, index) in contacts" :key="index" 
        @click="selectContact(contact)"
         :class="{ 'active-contact': contact.target === targetUserId }">
          <div class="contact-avatar">
            <img :src="contact.avatar" alt="头像">
          </div>
          <div class="contact-info">
            <div class="contact-name">{{ contact.username }}</div>
            <div class="contact-status">
              <span v-if="contact.isOnline" class="online-status">在线</span>
              <span v-else class="offline-status">离线</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-main">
    <!-- 头部区域 -->
    <div class="chat-header">
     
      <el-icon  @click="goBack"
        class="back"><Back />
      </el-icon>
    
      <h3>聊天室</h3>
      <el-tag type="info" size="small">
        {{ userRole === 1 ? '系统管理员' : 
           userRole === 2 ? '当前租客' : '当前房东'  
           }}
      </el-tag>
       <!-- 新增智能代理开关 -->
      <el-switch
        v-if="userRole === 3"
        v-model="autoReplyEnabled"
        active-text="智能代理"
        inactive-text="手动回复"
        style="margin-left: 15px"
      />
    </div>
    <!-- 消息主体区域 -->
  <div ref="messageContainer" class="chat-messages"> 
    <!-- 消息 -->
     <div
      v-for="(msg, index) in messages"
      :key="index"
      :class="['message-item', { 'self-message': isSelf(msg.user_id) }]"
     >
    <!-- 头像和时间容器 -->
    <div class="meta-container">
      <!-- 系统消息可以隐藏头像或显示特定图标 -->
      <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
    </div>   
    <!-- 消息气泡 -->
    <div :class="['message-bubble', { 'self': isSelf(msg.user_id) }]">
      <div class="message-content" v-if="msg.sender !=='hint'">{{ msg.content }}</div>
      <!-- 智能提示消息 -->
     <div v-if="msg.sender === 'hint'" class="hint-message">
      <el-button
          v-for="item in parseHintItems(msg.content)"
          :key="item.title"
          type="primary"
          plain
          size="small"
          @click="sendHintMessage(item.content)"
          class="hint-button"
        >
        {{ item.title }}
        </el-button>
    </div>
      <!-- 系统提示标签 -->
      <!-- <div v-if="msg.sender === 'system'" class="system-tag">系统提示</div> -->
    </div>
     </div>
  </div>


    <!-- 输入区域 -->
    <div class="chat-input-area">
      <el-input
        v-model="newMessage"
        type="textarea"
        :rows="3"
        placeholder="输入消息（按Ctrl+Enter发送）"
        @keydown.ctrl.enter="sendMessage"
        resize="none"
      />
      <el-button 
        type="primary" 
        @click="sendMessage"
        :disabled="!newMessage.trim()"
        class="send-button"
      >
        发送
      </el-button>
    </div>
  </div>
</div>
</template>

<script setup lang="ts">
import { ref,onMounted,onUnmounted,nextTick,watch,computed } from 'vue';
import { ElMessage } from 'element-plus';
import { io } from 'socket.io-client';
import apiClient from '@/api/api';
import { useRoute } from 'vue-router'; // 新增路由hook
import { useRouter } from 'vue-router'
import { Back } from '@element-plus/icons-vue'
// 新增智能代理开关
const autoReplyEnabled = ref(false);
const router = useRouter()
// 新增智能提示数据
const hintMessages = ref([
  { title: '询问租金', content: '请问这个房子的租金是多少？' },
  { title: '租期咨询', content: '最短租期是多久？' },
  { title: '设施询问', content: '房间有哪些配套设施？' },
  { title: '看房预约', content: '什么时候可以安排看房？' }
]);
// 新增滚动引用
const messageContainer = ref<HTMLElement>();
// 新增联系人示例数据
const contacts = ref<contact[]>([
  {
    target: 1,  // 使用target代替id
    username: '系统客服',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    isOnline: true  // 新增在线状态
  },
  {
    target: 2,
    username: '租客小王', 
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    isOnline: false
  },
  {
    target: 3,
    username: '房东李姐',
    avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    isOnline: true
  }
]);
//历史消息
interface historyMessage {
  id: number; // 消息ID
  user_id: number; // 用户ID
  role: number; // 用户角色 (1：管理员, 2: 租客, 3: 房东)
  target: number; // 目标用户ID
  content: string; // 消息内容
  timestamp: number; // 消息时间戳
}
// 定义消息接口
interface Message {
  id?: number;        // 消息ID（可选）
  user_id: number;    // 发送者ID
  role: number;       // 发送者角色
  target: number;     // 接收者ID
  sender: 'system' | 'user' | 'landlord'|'hint';  // 使用联合类型限定发件人类型
  content: string;
  timestamp: number;
}
//最近联系人
interface contact {
  target: number;
  username: string;
  avatar?: string;   //头像
  isOnline: boolean;
}
// 用户角色 (1：管理员, 2: 租客, 3: 房东)
const userRole = ref(Number(localStorage.getItem('userRole')));
console.log("状态"+userRole.value);
const route = useRoute();
const targetUserId = ref<number>(Number(route.query.targetId)||0); // 获取路由参数并转换类型
const targetUsername = ref<string>(route.query.landlordName?.toString() || `用户${targetUserId.value}`);
console.log("初始"+targetUserId.value);
console.log("初始"+targetUsername.value);

// 新增监听路由参数变化
watch(() => route.query.targetId, (newVal) => {
  console.log("切换路由路由"+newVal); // 打印新的 targetId
  targetUserId.value = Number(newVal);
  messages.value = [];
  hasMore.value = true; // 重置分页状态
  currentPage.value = 1; // 重置分页页码
  loading.value = false; // 重置加载状态
  // autoReplyEnabled.value = false; // 重置智能代理开关
  console.log(targetContactStatus.value,userRole.value,targetUserId.value)
  if(targetContactStatus.value===false && userRole.value===2 &&targetUserId.value!=1){
    // 切换联系人时重新加载智能提示
    console.log("重新加载智能提示");
    messages.value = [{
      user_id:targetUserId.value ,
      role: 3,
      target: Number(localStorage.getItem('userId')),
      sender: 'hint',
      content: JSON.stringify(hintMessages.value),
      timestamp: Date.now()
    }];
  }
  
  loadHistory(); // 路由变化时重新加载历史记录
});

// 新消息内容
const newMessage = ref('');

// 消息列表初始化为空
const messages = ref<Message[]>([]);

const currentuserId=localStorage.getItem('userId');
// WebSocket 连接
const socket = io(`http://localhost:5000/chat?userId=${currentuserId}`)
// 新增组件挂载/卸载逻辑
onMounted(() => {
  if(userRole.value==3){
   // 向后端发送状态变更通知
    socket.emit('proxy_status', {
      userId: Number(localStorage.getItem('userId')),
      is_ai: autoReplyEnabled.value // 发送当前状态
    });
  }
  // 发送连接请求并处理响应
  console.log("连接",localStorage.getItem('userId'));
  apiClient.post('chat/connect', { 
    userId: localStorage.getItem('userId'),
    role: userRole.value
  })
  .then((response) => {
    // ✅ 成功时打印服务器响应
    console.log('后端返回:', response.data.data);
    // 新增联系人列表处理
    if (response.data.data && response.data.data.recentContacts) {
      contacts.value = response.data.data.recentContacts.map((contact: contact)  => ({
        target: Number(contact.target),
        username: contact.username,
        avatar: contact.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        isOnline: contact.isOnline
      }));
      // console.log("联系人列表"+contacts.value[0].username+contacts.value[0].isOnline);
    }
    if(targetUserId.value==0){
      targetUserId.value=contacts.value[0].target;
    }
    
    console.log("目标用户"+targetUserId.value);
    ElMessage.success("成功加入聊天室");
    loadHistory(); // 调用加载历史消息方法
    // 创建带用户名的新联系人
    const routeContact = targetUserId.value > 0 ? {
    target: targetUserId.value,
    username: targetUsername.value,  // 使用路由参数中的用户名
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    isOnline: false
  } : null;
  // 合并联系人列表
   const mergedContacts = [...contacts.value]; // 先复制原有联系人列表

// 如果 routeContact 存在，并且目标用户不在已有联系人中，则插入
    if (routeContact && !mergedContacts.some(c => c.target === routeContact.target)) {
      console.log("插入");
     mergedContacts.unshift(routeContact); // 插入到最前面
  // 或者插到最后面：
  // mergedContacts.push(routeContact);
    }
    // 更新联系人列表
    contacts.value = mergedContacts;
    console.log("合并后的联系人列表：", contacts.value);
  })
  .catch((error) => {
    // ❌ 错误处理
    console.error('请求失败:', error.response?.data || error.message);
    ElMessage.error('进入聊天室失败');
  });
// 绑定 scroll 事件监听器
      const container = document.querySelector('.chat-messages');
      if (container) {
        container.addEventListener('scroll', handleScroll);
      } else {
        console.warn('.chat-messages 元素未找到');
      }
});
 // 新增在线状态监听
    
    socket.on('presence_update', (data: { userId: number; isOnline: boolean }) => {
    contacts.value = contacts.value.map(contact => 
      (Number(contact.target)) === data.userId ? { ...contact, isOnline: data.isOnline } : contact
    );
    console.log("监听在线状态"+data.userId+data.isOnline);
    console.log("联系人列表"+contacts.value[0].username+contacts.value[0].isOnline);
    
    
  });
// 处理滚动事件
    const handleScroll = () => {
      const container = document.querySelector('.chat-messages');
      if (container && container.scrollTop === 0 && hasMore.value) {
        loadHistory();
      }
    };


// 新增分页状态
const currentPage = ref(1);
const hasMore = ref(true);
const loading = ref(false);

// 加载历史消息方法
const loadHistory = async () => {
  if (!hasMore.value || loading.value) return;
  loading.value = true;
  try {
    const res = await apiClient.get('chat/history', {
      params: {
        userId: localStorage.getItem('userId'),
        role: userRole.value,
        target: targetUserId.value,
        page: currentPage.value,
        pageSize: 10
      }
    });

    const historyMessages = res.data.data.messages.map((msg: historyMessage) => ({
      user_id: msg.user_id,
      role: msg.role,
      target: msg.target,
      sender: msg.role === 1 ? 'system' : msg.role === 2 ? 'user' : 'landlord',
      content: msg.content,
      timestamp: msg.timestamp
    }));

    if (historyMessages.length < 10) {
      hasMore.value = false;
    }
    // 追加历史消息到现有列表
    messages.value = [...historyMessages,...messages.value];
    currentPage.value++;
    scrollToBottom(); // 新增滚动调用

  } catch (err) {
    console.error('获取历史消息失败:', err);
    ElMessage.warning('历史记录加载失败');
  } finally {
    loading.value = false;
  }
};

onUnmounted(() => {
  socket.disconnect(); // 组件卸载时断开连接
  socket.off('connect'); // 移除事件监听
  socket.off('disconnect');
  socket.off('response');
  socket.off('chat_response');
  socket.off('presence_update');
  // socket.off('heartbeat');
});
// 监听连接打开事件
socket.on('connect', () => {
  console.log('Connected to WebSocket server');
   // 每30秒发送心跳包：维持长连接，防止超时断开
   setInterval(() => { 
     // 发送包含用户ID和角色的心跳数据
     socket.emit('heartbeat', { 
       userId: localStorage.getItem('userId'),  // 从本地存储获取当前用户ID
       role: userRole.value                       // 当前用户角色（1/2/3）
     }); 
   }, 30000);                                     // 30秒间隔（30000毫秒）
});
// 监听连接关闭事件
socket.on('disconnect', () => {
  console.log('Disconnected from WebSocket server');
  // 断线时将所有联系人标记为离线：遍历contacts数组
  console.log("用户断线")
   contacts.value = contacts.value.map(c => ({ 
     ...c,                // 保留原有属性
     isOnline: false      // 强制设置isOnline为false
   })); 
  
});



// 发送消息方法
const sendMessage = () => {
  if (!newMessage.value.trim()) return;
  // // 自动代理
  // if (autoReplyEnabled.value && userRole.value === 2) {
  //   console.log("自动代理")
  //   sendHintMessage(newMessage.value.trim());
  //   return;
  // }
  // 添加新消息到列表
  messages.value.push({
    user_id: Number(localStorage.getItem('userId')) || 0,
    role: userRole.value,
    target: targetUserId.value,
    sender: userRole.value === 1? 'system' : userRole.value===2 ?'user':'landlord',
    content: newMessage.value.trim(),
    timestamp: Date.now()
  });
//构建发送数据 用户编号-角色-内容-发送目标编号-时间
  const sendData = {
    user_id: Number(localStorage.getItem('userId')),
    role: userRole.value,
    content: newMessage.value.trim(),
    target: targetUserId.value,       
    timestamp: Date.now(),
    ai: 0
  };
console.log("发送数据"+sendData.user_id,sendData.role,sendData.content,sendData.timestamp);
socket.emit('sendmessage', sendData);
  newMessage.value = ''; // 清空输入框
  scrollToBottom(); // 新增滚动调用
};

// 时间格式化方法
const formatTime = (timestamp?: number) => {
  if (!timestamp) return '';
  return new Date(timestamp).toLocaleString([], { 
    month: '2-digit',     // 新增月份
    day: '2-digit',       // 新增日期
    hour: '2-digit',
    minute: '2-digit'
  });
};
// 监听消息事件
socket.on('chat_response', (response) => {
  console.log("收到消息")
  console.log('Received response:', response.data);
  if(Number(response.data.target)!=Number(localStorage.getItem('userId'))){
    console.log(response.data.target)
    console.log("不是目标用户")
    return;
  }
  // 处理服务器返回的消息
  messages.value.push({
    user_id: response.data.user_id,
    role: response.data.role,
    target: response.data.target,
    sender: response.data.role === 1? 'system' : response.data.role===2 ?'user':'landlord',
    content: response.data.content,
    timestamp: response.data.timestamp
  });
  scrollToBottom(); // 新增滚动调用
})
//监听AI返回消息
socket.on('ai_response', (response) => {
  console.log("收到AI消息")
  console.log('Received response:', response.data);
  // &&Number(response.data.user_id)!=Number(localStorage.getItem('userId'))
  if(Number(response.data.user_id)!=targetUserId.value 
  &&Number(response.data.user_id)!=Number(localStorage.getItem('userId'))){
    console.log(response.data.target)
    console.log("不是目标用户")
    return;
  }
  // 处理服务器返回的消息
  messages.value.push({
    user_id: response.data.user_id,
    role: response.data.role,
    target: response.data.target,
    sender: response.data.role === 1?'system' : response.data.role===2?'user':'landlord',
    content: response.data.content,
    timestamp: response.data.timestamp
  });
})
  
// 判断是否是当前用户发送的消息
const isSelf = (user_id: number) => {
    // 假设当前用户角色为 'user'
    return user_id === Number(localStorage.getItem('userId'));
  }

  // 选择联系人方法
  const selectContact = (contact: contact) => {
    targetUserId.value = contact.target; // 更新目标用户ID
    ElMessage.info('目标用户变更');
   
    targetUsername.value = contact.username; // 更新目标用户名
    //重新跳转
    router.push({ path: '/chat', query: { targetId: contact.target } })
  }


  // 自动滚动方法
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};
// 新增返回方法
const goBack = () => {
  router.push({ path: '/' })
}
// 智能提示发送消息解析
const parseHintItems = (content: string) => {
  try {
    return JSON.parse(content);
  } catch (e) {
    console.error('解析 hint 内容失败', e);
    return [];
  }
};
// 智能提示发送消息
const sendHintMessage = (message: string) => {
  messages.value.push({
    user_id: Number(localStorage.getItem('userId')) || 0,
    role: userRole.value,
    target: targetUserId.value,
    sender: userRole.value === 1? 'system' : userRole.value===2 ?'user':'landlord',
    content: message,
    timestamp: Date.now()
  });
  //构建发送数据 用户编号-角色-内容-发送目标编号-时间
  const sendData = {
    user_id: Number(localStorage.getItem('userId')),
    role: userRole.value,
    content: message,
    target: targetUserId.value,       
    timestamp: Date.now(),
    ai: 1
  };
console.log("发送数据"+sendData.user_id,sendData.role,sendData.content,sendData.timestamp);
socket.emit('sendmessage', sendData);
  newMessage.value = ''; // 清空输入框
  scrollToBottom(); // 新增滚动调用
 
}
// 新增目标联系人状态检测
const targetContactStatus = computed(() => {
  console.log("检测状态"+targetUserId.value)
  const currentContact = contacts.value.find(c => c.target === targetUserId.value);
  return currentContact?.isOnline;
});
// 监听联系人离线状态
// watch(targetContactStatus, (isOnline) => {
//   if (!isOnline && userRole.value===2 && targetUserId.value!=1) {
//     autoReplyEnabled.value = true;
//     ElMessage.info('检测到联系人离线，已启用自动代理');
//   }
//   else {
//     autoReplyEnabled.value = false;
//     ElMessage.info('检测到联系人在线，已禁用自动代理');
//   }
// });
// 监听智能代理开关变化
watch(autoReplyEnabled, (enabled) => {
if (userRole.value === 3) { // 仅房东角色处理
    // 向后端发送状态变更通知
    socket.emit('proxy_status', {
      userId: Number(localStorage.getItem('userId')),
      is_ai: enabled
    });
    // 添加系统提示消息
    const statusText = enabled ? '已启用智能代理' : '已禁用智能代理';
    ElMessage.info(statusText);
    
    // 调试日志
    console.log(`代理状态变更: ${statusText}`, 
      `目标用户: ${targetUserId.value}`);
  }
});

</script>

<style scoped>

/* 主容器样式 */
.chat-container {
  height: 80vh;
  max-width: 1200px;
  margin: 60px auto;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
  flex-direction: row;
  /* background: url('@/assets/bgchat2.png') no-repeat center center; */

}
.contact-sidebar {
   height: 80vh;
  width: 350px;
  /* margin: 60px auto; */
  box-sizing: border-box;
  border-right: 1px solid #e4e7ed;
  background: #fff;
  /* border: 1px solid #e4e7ed; */
  border-radius: 8px;
  /* display: flex; */
  flex-direction: row;
}
.sidebar-header {
  margin-bottom: 16px;
}

.contact-list {
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.contact-item:hover {
  background-color: #e4e7ed;
}

.contact-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.contact-info {
  margin-left: 12px;
}

.contact-name {
  font-weight: bold;
}

.contact-status span {
  font-size: 12px;
  color: #999;
}

.online-status {
  color: green;
}

.offline-status {
  color: red;
}


.chat-main {
  flex: 1;
  height: 80vh;
  max-width: 850px;
  /* margin: 60px auto; */
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}
/* 头部样式 */
.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 12px;
  /* 新增弹性布局设置 */
  flex-wrap: wrap;
  row-gap: 8px;
}
/* 新增响应式调整 */
@media (max-width: 768px) {
  .chat-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
/* 消息区域样式 */
.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.message-item {
 display: flex;
  flex-direction: column;
  align-items: flex-start;
  max-width: 70%;
  width: fit-content;
  align-self: flex-start;
}

.message-item.self-message {
   align-self: flex-end;
  align-items: flex-end;
}

/* 消息行布局 */
.message-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin: 8px 0;
}

/* 元信息容器 */
.meta-container {
  display: flex;
  flex-direction: row;  /* 改为横向排列 */
  align-items: center;
  gap: 8px;            /* 添加间距 */
  width: auto;          /* 取消固定宽度 */
}

.message-time {
  order: -1;           /* 将时间移到头像左侧 */
  font-size: 12px;
  color: #666;
  margin: 0;
}

.message-avatar {
  order: 1;            /* 头像在右侧 */
}
/* 调整时间显示位置 */
.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: center;
}

/* 消息气泡样式 */
.message-bubble {
  max-width: fit-content;  /* 根据内容自动调整宽度 */
  min-width: 120px;        /* 设置最小宽度 */
  padding: 3px 3px;      /* 优化内边距 */
  .message-content {
    font-size: 15px;  /* 增加字体大小 */
    line-height: 2.4;  /* 调整行高 */
    white-space: pre-wrap;  /* 保留换行但自动换行 */
  }
  border-radius: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  
  
}
/* 自己发出的消息 */
.message-bubble.self {
  max-width: fit-content;  /* 根据内容自动调整宽度 */
  min-width: 120px;        /* 设置最小宽度 */
  padding: 3px 3px;      /* 优化内边距 */
  .message-content {
    font-size: 15px;  /* 增加字体大小 */
    line-height: 2.4;  /* 调整行高 */
    white-space: pre-wrap;  /* 保留换行但自动换行 */
  }
  border-radius: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  
  
    background: #7eb5ec;
    color: white;
    margin-left: auto;
    border-color: transparent;
  
}
.message-bubble.system {
  position: relative;
  padding: 20px 16px 28px;
  background: #f0f9eb;
  border-color: #e1f3d8;
}

.system-tag {
  position: absolute;
  top: 6px;
  right: 12px;
  font-size: 12px;
  color: #67c23a;
  opacity: 0.8;
}

.message-bubble.system .message-time {
  position: absolute;
  bottom: 6px;
  left: 12px;
  color: #909399;
}

/* 输入区域样式 */
.chat-input-area {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  position: relative;
  
  .send-button {
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
}
/* 时间显示样式 */
.message-time {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  text-align: right;
}
.active-contact {
  background-color: #f5f7fa !important;
  border-left: 4px solid #409eff;
  font-weight: 600;
}

.active-contact:hover {
  background-color: #ebeef5 !important;
}
/* 返回按钮 */
.back {
  margin-right: 12px;
  color: #020c17;
  transition: all 0.3s ease; 
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: transparent;

  &:hover {
    color: #9aa0a6;
    background-color: #e8eaea;
  }

  &:active {
    transform: scale(0.9);
    color: #7a8288;
    background-color: #dbe0e2;
  }
}
.hint-message {
  margin: 12px 0;
  display: flex;
  gap: 8px;
  font-size: large;
  /* flex-direction: column;  改为纵向排列 */
  
  justify-content: center; /* 或 start / flex-start / space-around 等 */
}

.hint-button {
  width: auto;        /* 自动宽度 */
  flex-grow: 1;       /* 允许按钮扩展填充空间 */
  white-space: nowrap; /* 禁止文字换行 */
  text-overflow: ellipsis; /* 文字过长显示省略号 */
  overflow: hidden;    /* 隐藏溢出内容 */
  padding: 8px 12px;  /* 统一内边距 */
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    background: #409eff !important;
    color: white !important;
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  }
}
</style>